package com.hpxx.ylzswl.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSON;
import com.hpxx.ylzswl.R;
import com.hpxx.ylzswl.activity.OrderDetailsAvtivity;
import com.hpxx.ylzswl.adapter.OrderAdapter;
import com.hpxx.ylzswl.base.BaseEvent;
import com.hpxx.ylzswl.base.BaseFragment;
import com.hpxx.ylzswl.bean.OrderListBean;
import com.hpxx.ylzswl.event.OrderListEvent;
import com.hpxx.ylzswl.event.OrderTabEvent;
import com.hpxx.ylzswl.event.OrderTabListEvent;
import com.hpxx.ylzswl.https.HttpAddress;
import com.hpxx.ylzswl.https.RequestParams;
import com.hpxx.ylzswl.info.ManageInfo;
import com.hpxx.ylzswl.utils.ConstantsUtils;
import com.hpxx.ylzswl.utils.MyCache;
import com.hpxx.ylzswl.views.NoScrollingListView;
import com.universal.frame.generalutils.GeneralUtil;
import com.universal.frame.generalutils.JsonUtil;
import com.universal.frame.generalutils.NetWorkUtil;
import com.universal.frame.generalutils.ToastUtil;
import com.universal.frame.okhttp.OKHttpUtils;
import com.universal.frame.okhttp.ResultCallBack;
import com.universal.frame.pulltorefresh.PullToRefreshBase;
import com.universal.frame.pulltorefresh.PullToRefreshScrollView;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Request;

/**
 * Created by Administrator on 2017/11/7.
 */

public class OrderItemFragment extends BaseFragment implements
        PullToRefreshBase.OnRefreshListener2,AdapterView.OnItemClickListener,ResultCallBack{

    private int state;
    private List<OrderListBean> list = new ArrayList<OrderListBean>();
    private OrderAdapter adapter;
    private PullToRefreshScrollView pull_refresh_scrollview;
    private NoScrollingListView nsl_list;
    private int pageIndex = 0;
    private boolean toRefresh = true;
    public static OrderItemFragment newInstance(int state) {
        OrderItemFragment fragment = new OrderItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ConstantsUtils.FRAGMENT_FLG, state);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.state = getArguments().getInt(ConstantsUtils.FRAGMENT_FLG);
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_item_order;
    }

    @Override
    public void initView(View view) {
        pull_refresh_scrollview = view.findViewById(R.id.pull_refresh_scrollview);
        nsl_list = view.findViewById(R.id.nsl_list);
        if (NetWorkUtil.isNetWorkConnected(getContext())) {
            orderListPost("1",pageIndex);
        }else {
            MyCache aCache = MyCache.get(getContext());
            if (aCache.getAsObject("order1") !=null){
                //使用getAsObject()，直接进行强转
                list = (ArrayList<OrderListBean>) aCache.getAsObject("order1");
                Log.e("lzxxxxxxxxxx", "initView: "+list.get(0).doctorRealname);
                ToastUtil.showToast(getContext(), R.string.toast_network_connection_tips);
            }else {
                ToastUtil.showToast(getContext(), R.string.toast_network_connection_tips);
            }

        }
        initScrollView();

    }
    private void orderListPost(String tabType, int pageIndex){
        OKHttpUtils.postAsync(getContext()
                , HttpAddress.ORDER_LIST_URL
                , new RequestParams(getContext()).getOrderListParams(3, tabType, pageIndex,""), this
                ,true,1);
    }
    public void initScrollView() {
        this.pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setPullLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_pull_label_up));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setRefreshingLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_refreshing_label));
        pull_refresh_scrollview.getLoadingLayoutProxy(false, true)
                .setReleaseLabel(
                        this.getResources().getString(
                                R.string.pull_to_refresh_release_label));

        pull_refresh_scrollview.setMode(PullToRefreshBase.Mode.BOTH);//both  可以上拉、可以下拉
        pull_refresh_scrollview.setOnRefreshListener(this);
        nsl_list.setOnItemClickListener(this);
        adapter = new OrderAdapter(getActivity(),list);
        nsl_list.setAdapter(adapter);
    }


    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pageIndex = 0;
        orderListPost("1",pageIndex);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        if(toRefresh){
            pageIndex++;
            orderListPost("1",pageIndex);
        }else{
            ToastUtil.showToast(getActivity(),"没有更多数据");
            pull_refresh_scrollview.onRefreshComplete();
        }
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (NetWorkUtil.isNetWorkConnected(getContext())) {
            int position = i ;
            Intent intent = new Intent(getActivity(), OrderDetailsAvtivity.class);
            intent.putExtra("ORDER_ID",list.get(position).orderId);
            startActivity(intent);
        }else {
            ToastUtil.showToast(getContext(), R.string.toast_network_connection_tips);
        }

    }


    @Override
    public void onSuccess(String response, int flag) {
        int status = JsonUtil.getInt(response, "status", 0);
        try {
            switch (flag) {
                case 1:
                    OrderListDetail(response);
                    break;
            }
        } catch (Exception e) {
            GeneralUtil.tryShow(getContext(), e);
        }
    }

    private void OrderListDetail(String response) {
        Log.e("lzx", "shopDetail: " + response);
        pull_refresh_scrollview.onRefreshComplete();
        int status = JsonUtil.getInt(response, "status", 0);
        if (status == 1){
            String data = JsonUtil.getString(response,"data","");
            ManageInfo info = JSON.parseObject(data, ManageInfo.class);
            Log.i("tag", "size = " + info.orderList.size());
            if (info.orderList != null) {
                if (info.orderList.size() >= 0) {
                    if (pageIndex == 0) {
                        list.clear();
                        list.addAll(info.orderList);
                        MyCache aCache = MyCache.get(getContext());
                        aCache.put("order1", (Serializable) list);
                    } else {
                        list.addAll(info.orderList);
                    }
                }
                adapter.notifyDataSetChanged();
                EventBus.getDefault().post(new OrderTabEvent());
                if(info.orderList.size() < 10){
                    toRefresh = false;
                }else{
                    toRefresh = true;
                }

            }
//            else {
//                list.clear();
//                MyCache aCache = MyCache.get(getContext());
//                aCache.put("order1", (Serializable) list);
//            }

        }else {
            String msg = JsonUtil.getString(response,"msg","");
            ToastUtil.showToast(getActivity(),msg);
        }
    }

    @Override
    public void onFailure(Request request, IOException e, int flag) {
        pull_refresh_scrollview.onRefreshComplete();
//        MyCache aCache = MyCache.get(getContext());
//        if (aCache.getAsObject("order1") !=null){
//            //使用getAsObject()，直接进行强转
//            list = (ArrayList<OrderListBean>) aCache.getAsObject("order1");
//            initScrollView();
//            Log.e("lzxxxxxxxxxx", "initView: "+list.get(0).doctorRealname);
//            ToastUtil.showToast(getContext(), R.string.toast_network_connection_tips);
//        }else {
//            ToastUtil.showToast(getContext(), R.string.toast_network_connection_tips);
//        }

    }
    @Override
    @Subscribe
    public void onEventMainThread(BaseEvent event) throws IOException {
        super.onEventMainThread(event);
        if (event instanceof OrderListEvent) {
            pageIndex = 0;
            orderListPost("1",pageIndex);
        }
        if (event instanceof OrderTabListEvent) {
            pageIndex = 0;
            orderListPost("1",pageIndex);
        }
    }
}
